package cn.gs.reflect;

// @author gs
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodProxy;

public class ProxyTool implements IProxy {

    Object o;

    public ProxyTool(Object o) {
        this.o = o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(o, args);
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] os, MethodProxy mp) throws Throwable {
        return mp.invokeSuper(o, os);
    }
    static Enhancer en = null;

    public static <T> T create(IProxy o, Class<T> clazz) {
        if (clazz.isInterface()) {
            return (T) Proxy.newProxyInstance(clazz.getClassLoader(),
                    new Class[]{clazz}, o);
        } else {
            if (en == null) {
                en = new Enhancer();
                en.setSuperclass(clazz);
            }
            en.setCallback(o);
            return (T) en.create();
        }
    }

    public static <T> T create(Object o, Class<T> clazz) {
        return create(new ProxyTool(o), clazz);
    }

    public static boolean isProxy(Object o) {
        if (o == null) {
            return false;
        }
        if (Proxy.isProxyClass(o.getClass())) {// Java Proxy
            return true;
        }
        try {
            Field h = o.getClass().getDeclaredField("CGLIB$CALLBACK_0");
            return h != null;
        } catch (Throwable ex) {
            return false;
        }
    }

    public static Object getProxyTarget(Object o) {
        if (o != null) {
            if (Proxy.isProxyClass(o.getClass())) {// Java Proxy
                return Proxy.getInvocationHandler(o);
            }
            try {
                Field h = o.getClass().getDeclaredField("CGLIB$CALLBACK_0");
                if (h != null) {
                    h.setAccessible(true);
                    return h.get(o);
                }
            } catch (Throwable ex) {
                //Logger.getLogger(ProxyTool.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
}
